# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *
from datetime import datetime, timedelta

import json
import socket



def send_data_to_java(data):
    # Java服务器的IP地址和端口号
    JAVA_SERVER_IP = 'localhost'
    JAVA_SERVER_PORT = 8000  # 请替换为实际的Java服务器端口

    # 创建socket对象
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接到Java服务器
        sock.connect((JAVA_SERVER_IP, JAVA_SERVER_PORT))

        # 将数据转换为字节串（假设数据是字符串）
        data_bytes = data.encode('utf-8')

        # 发送数据到Java服务器
        sock.sendall(data_bytes)

        # （可选）接收Java服务器的回复（如果有的话）
        # response = sock.recv(1024).decode('utf-8')
        # print(f"Received response: {response}")

    finally:
        # 关闭socket连接
        sock.close()


class Quote:
    def __init__(self, bid_p: float, bid_v: int, ask_p: float, ask_v: int,
                 bid_q: dict, ask_q: dict):
        self.bid_p = bid_p
        self.bid_v = bid_v
        self.ask_p = ask_p
        self.ask_v = ask_v
        self.bid_q = bid_q
        self.ask_q = ask_q

class TickClass:
    def __init__(self, quotes: list[Quote], symbol: str, created_at: datetime, price: float, open_price: float,
                 high_price: float, low_price: float, cum_volume: int, cum_amount: float, cum_position: int,
                 last_amount: float, last_volume: int, trade_type: int, flag: int, receive_local_time: float, iopv: float):
        self.quotes = quotes
        self.symbol = symbol
        self.created_at = created_at
        self.price = price
        self.open = open_price
        self.high = high_price
        self.low = low_price
        self.cum_volume = cum_volume
        self.cum_amount = cum_amount
        self.cum_position = cum_position
        self.last_amount = last_amount
        self.last_volume = last_volume
        self.trade_type = trade_type
        self.flag = flag
        self.receive_local_time = receive_local_time
        self.iopv = iopv



def init(context):
    # 订阅浦发银行, bar频率为一天和一分钟
    # 订阅订阅多个频率的数据，可多次调用subscribe
    # subscribe(symbols='SHSE.000300', frequency='1d')
    # subscribe(symbols='SHSE.000300', frequency='60s')
    subscribe(symbols='SHSE.512000', frequency='tick',count=1,fields='symbol, price, open,high,low', format='row')


def on_tick(context, tick):

    # 打印tick数据
    data = context.data(symbol=tick['symbol'], frequency='tick', count=1)
    print("data:",data)
    json_string = json.dumps(data)
    send_data_to_java(json_string)




# def on_bar(context, bars):
#     for bar in bars:
#         # 打印bar数据
#         print(f'bar {bar["frequency"]} :', bar, sep='\n')


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
        backtest_match_mode市价撮合模式，以下一tick/bar开盘价撮合:0，以当前tick/bar收盘价撮合：1
    '''
    backtest_start_time = str(datetime.now() - timedelta(weeks=1))[:19]
    backtest_end_time = str(datetime.now())[:19]
    run(strategy_id='4de2bb70-fd25-11ee-b13b-00ffaf12d465',
        filename='sub_tick.py',
        mode=MODE_LIVE,
        token='9f78838426fc80c2d8b9b284d1e2b78acf41234a',
        backtest_start_time=backtest_start_time,
        backtest_end_time=backtest_end_time,
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001,
        backtest_match_mode=1)
